package com.qunar.wan.common_api.model;


import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * User: cyoung Date: 11/27/13 Time: 10:36 AM
 */
public class Query extends LinkedHashMap<Object, Object> implements Serializable {
    private static final long serialVersionUID = 4251575591154311690L;
    private static final String SORTS_KEY = "sorts";

    public Query() {
    }

    public Query(final Object key, final Object value) {
        super.put(key, value);
    }

    private Object checkAndPut(final Object key, final Object value) {

        return super.put(key, value);
    }

    public Query fill(final String key, final Object value) {
        checkAndPut(key, value);
        return this;
    }

    private List<Sort> getSorts() {
        List<Sort> sorts = (List<Sort>) get(SORTS_KEY);
        if (sorts == null) {
            sorts = new LinkedList<Sort>();
            super.put(SORTS_KEY, sorts);
        }
        return sorts;
    }

    public Query addSort(Sort sort) {
        getSorts().add(sort);
        return this;
    }

    public Query and(Query query) {
        for (Map.Entry entry : query.entrySet()) {
            if (entry.getKey() != null && entry.getValue() != null) {
                this.put(entry.getKey(), entry.getValue());
            }
        }
        return this;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder("[");
        for (Map.Entry entry : this.entrySet()) {
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append(" ");
        }
        return stringBuilder.append("]").toString();
    }

}
